<template>
    <view class="page-index">
        <yz-hepler></yz-hepler>
        <!-- 类目 -->
        <category-bar ref="category-bar" @change="toCategoryPage" :top="scrollTop"></category-bar>
        <view class="header">
            <image mode="widthFix" class="subsidy-bg" src="/static/images/subsidy-bg-top.png" />
            <view class="top-tips">
                <image class="top-tips__cover" src="/static/icon/top-tab.png" />
                <view class="top-tips__item"
                    >累计已发{{ conf.totalGeSubsidiestAmount || 0 }}亿元</view
                >
                <view class="top-tips__item active"
                    >今日已发{{ conf.todayGetSubsidiesAmount || 0 }}万元</view
                >
                <view class="top-tips__item">每日{{ conf.startVieTime || 0 }}点开抢</view>
            </view>
            <!-- 补贴金 -->
            <view class="subsidy-price">
                <image
                    mode="widthFix"
                    class="subsidy-price-bg"
                    src="/static/images/subsidy-price-bg.png"
                />

                <view class="detail">
                    <count-to
                        class="value"
                        :startVal="userInfo.old_subsidiesAmount || 0"
                        :endVal="userInfo.subsidiesAmount || 100"
                        :duration="1000"
                    ></count-to>

                    <view class="countdown">
                        <view v-if="isDownTime">
                            <cl-countdown
                                :splitor="[':', ':', ':']"
                                :layout="['hour', 'minute', 'second']"
                                is-millisecond
                                :datetime="endTime"
                                @done="onCountdownDone"
                            ></cl-countdown>
                        </view>

                        <view class="time-box" v-else>
                            <view class="time-box__li">00</view>
                            <view class="time-box__pian">:</view>
                            <view class="time-box__li">00</view>
                            <view class="time-box__pian">:</view>
                            <view class="time-box__li">00</view>
                            <view class="time-box__pian">:</view>
                            <view class="time-box__li">00</view>
                        </view>

                        <text style="margin-left: 10rpx">后失效</text>
                    </view>
                </view>
            </view>
        </view>

        <view class="container">
            <!-- 轮播图 -->
            <banner ref="banner"></banner>

            <!-- 天天特价  掩藏 -->
            <!-- <view class="on-sale" v-if="false">
                <on-sale ref="on-sale"></on-sale>
            </view> -->

            <!-- 天天特价 -->
            <view class="rank-goods">
                <rank-goods ref="rank-goods"></rank-goods>
            </view>

            <!-- 选项卡 -->
            <view class="goods-list">
                <!-- 标题 -->
                <view class="goods-list__header">
                    <text>榜单好货</text>

                    <view class="countdown">
                        <image class="bg" src="@/static/images/end-time.png" />

                        <view class="det">
                            <cl-countdown
                                :splitor="[':', ':', '']"
                                :layout="['hour', 'minute', 'second']"
                                :datetime="todayEndTime"
                            ></cl-countdown>
                        </view>
                    </view>
                </view>

                <template>
                    <goods-item
                        v-for="(item, index) in list"
                        :key="index"
                        :item="item"
                        :index="index"
                        type="xsyh"
                    ></goods-item>
                </template>

                <!-- 加载更多 -->
                <cl-loadmore
                    background-color="transparent"
                    color="#fff"
                    :loading="loading"
                    :finish="finish"
                    :divider="false"
                    v-if="list.length != 0"
                ></cl-loadmore>
            </view>
        </view>

        <!-- 补贴规则 -->
        <view class="popup-rules">
            <rules ref="rules"></rules>
        </view>

        <!-- 加载框 -->
        <cl-loading-mask text="拼命加载中" fullscreen :loading.sync="loading"></cl-loading-mask>

        <!-- 回到顶部 -->
        <back-top v-if="scrollTop > 400" />

        <!-- 现金红包 -->
        <view class="popup-red-package">
            <popup-red-package ref="popup-red-package" @refresh="allRefresh"></popup-red-package>
        </view>

        <!-- 分享 -->
        <share-popup ref="share-popup"></share-popup>

        <!-- 进群 -->
        <group-btn></group-btn>
    </view>
</template>

<script>
import { mapGetters } from 'vuex';
import Clipboard from 'clipboard';
import moment from 'moment';

import GoodsItem from './components/goods-item';
import Rules from './components/rules';
import BalancePopup from './components/balance-popup';
import BackTop from './components/back-top';
import SharePopup from './components/share';
import CategoryBar from './components/category-bar';
import OnSale from './components/on-sale';
import RankGoods from './components/rank-goods';
import Banner from './components/banner';
import PopupRedPackage from './components/red-package';
import GroupBtn from './components/group';
import CountTo from '@/components/dash-countTo/dash-countTo';

import RedPackage from '@/mixins/red-package';
import Share from '@/mixins/share';
var plugin = requirePlugin('yz-plugin');
export default {
    components: {
        GoodsItem,
        Rules,
        BalancePopup,
        BackTop,
        SharePopup,
        CategoryBar,
        OnSale,
        RankGoods,
        Banner,
        PopupRedPackage,
        CountTo,
        GroupBtn
    },

    mixins: [Share, RedPackage],

    data() {
        return {
            current: 0,
            loading: false,
            list: [],
            scrollTop: 0,
            endTime: '',
            todayEndTime: moment().format('YYYY-MM-DD 23:59:59'),
            totb: {
                visible: false
            },
            selects: {
                category: ''
            },
            categoryMenu: {
                visible: false
            },
            pagination: {
                page: 1,
                size: 20,
                total: 0
            },
            loading: false,
            finish: false
        };
    },

    computed: {
        ...mapGetters(['userInfo', 'conf', 'token', 'app', 'channelId', 'pId']),

        isDownTime() {
            if (Number(this.userInfo.subsidiesAmount) > 0) {
                return true;
            } else {
                return false;
            }
        }
    },

    onPullDownRefresh() {
        this.allRefresh();
    },

    onReachBottom() {
        if (!this.finish) {
            this.refresh({
                page: this.pagination.page + 1
            });
        }
    },

    onPageScroll(e) {
        this.scrollTop = e.scrollTop;
    },

    onLoad(options) {
        if (!uni.getStorageSync('userInfo').id) {
            this.$store.commit('CLEAR_TOKEN');
        }
        // 初始化 抽纸组件
        plugin.helper.init(options);
        // console.log('this.app', this.app);
        // console.log('this.channelId', this.channelId);
        // console.log('this.pId', this.pId);

        if (options.scene) {
            let str = decodeURIComponent(options.scene);

            str.split('&').map(e => {
                let [key, value] = e.split('=');

                options[key] = value;
            });
        }

        // console.log('options', options);

        if (!this.app && options.app) {
            this.$store.commit('SET_APP', options.app);
        }
        if (!this.channelId && options.channelId) {
            this.$store.commit('SET_CHANNELID', options.channelId);
        }
        if (!this.pId && options.pId) {
            this.$store.commit('SET_PID', options.pId);
        }
        uni.reportAnalytics('enter_index');

        /*
        接收点亮家乡小程序 传的usereId用户id  dlSubsidies补贴金金额  有数据调取接口
        */

        if (this.token) {
            if (options.dlUserId) {
                this.bindDlUser(options.dlUserId);
            }
            if (options.dlSubsidies) {
                this.receiveDlMoney(options.dlSubsidies);
            }
        }
    },

    onHide() {
        uni.reportAnalytics('background_index');
    },

    onShow() {
        this.$store.dispatch('addVisitRecord');
    },

    mounted() {
        this.scrollTop = 0;

        if (this.token) {
            this.$store
                .dispatch('getUserInfo')
                .then(res => {
                    if (res.user.subsidiesAmount == 0) {
                    }
                })
                .catch(err => {
                    uni.showToast({
                        title: err,
                        icon: 'none'
                    });
                });
        } else {
            // this.$refs['popup-red-package'].open();
        }

        // 开始加载
        this.loading = true;
        // 获取数据
        this.refresh(this.params);
        this.getConfig();
    },

    methods: {
        async allRefresh() {
            this.$refs['banner'].refresh();
            this.$refs['category-bar'].refresh();
            // this.$refs['on-sale'].refresh();
            this.$refs['rank-goods'].refresh();
            this.getConfig();
            await this.refresh({
                page: 1
            });

            uni.stopPullDownRefresh();
        },
        bindDlUser(id) {
            if (uni.getStorageSync('userInfo').id) {
                uni.request({
                    url: 'https://myhome.xmonecode.com/api/app/user/bindJljUser',
                    header: {
                        Authorization: (this.token || uni.getStorageSync('token') || '').replace(
                            /"/g,
                            ''
                        )
                    },
                    data: {
                        userId: id,
                        jljUserId: uni.getStorageSync('userInfo').id
                    },
                    success: res => {
                        if (res.data.code == 1000) {
                            uni.showToast({
                                title: '绑定成功',
                                icon: 'none'
                            });
                        } else {
                            uni.showToast({
                                title: res.data.message,
                                icon: 'none'
                            });
                        }
                    },
                    fail: err => {
                        console.log(err);
                    }
                });
            }
        },
        // 调取点亮家乡小程序的领取补贴金接口
        receiveDlMoney(amount) {
            this.$service.wxjlj
                .addUserSubsidies({ amount })
                .then(res => {
                    uni.showToast({
                        title: '添加补贴金成功',
                        icon: 'none'
                    });
                    this.$store.dispatch('getUserInfo');
                })
                .catch(err => {
                    uni.showToast({
                        title: err.message,
                        icon: 'none'
                    });
                });
        },
        getConfig() {
            // 获取配置
            this.$store
                .dispatch('getConf')
                .then(res => {
                    this.loading = false;
                    this.startCountdown();
                })
                .catch(err => {
                    if (err.indexOf('登录失效') >= 0) {
                        this.$store.commit('CLEAR_TOKEN');
                        this.$refs['popup-red-package'].open();
                    }
                    this.loading = false;
                });
        },
        startCountdown() {
            let t = Number(this.conf.countDownTime || '60') || '60';
            let now = null;

            if (t != uni.getStorageSync('countdown_mode')) {
                uni.removeStorageSync('countdown');
            }

            if (t < 0) {
                now = moment().format('YYYY-MM-DD 23:59:59');
            } else {
                if (isNaN(t)) {
                    t = 60;
                }
                now = moment()
                    .add(t, 'minute')
                    .format('YYYY-MM-DD HH:mm:ss');
            }

            let endTime = uni.getStorageSync('countdown');

            if (!endTime) {
                endTime = now;
            } else {
                if (moment(endTime).isBefore(moment())) {
                    endTime = now;
                }
            }

            uni.setStorageSync('countdown', endTime);
            uni.setStorageSync('countdown_mode', t);

            this.endTime = endTime;
        },

        onCountdownDone() {
            uni.removeStorageSync('countdown');
            uni.removeStorageSync('countdown_mode');
            this.startCountdown();
        },

        refresh(params = {}) {
            this.loading = true;
            const { page, size } = this.pagination;

            return this.$service.wxjlj
                .page({ page, size, ...params })
                .then(res => {
                    if (!params.page || params.page == 1) {
                        this.list = res.list;
                    } else {
                        this.list.push(...res.list);
                    }

                    this.finish = this.list.length == res.pagination.total;
                    this.pagination = res.pagination;
                    this.loading = false;
                })
                .catch(({ message }) => {
                    uni.showToast({
                        title: message,
                        icon: 'none'
                    });
                    this.loading = false;
                });
        },

        toCategoryPage(id) {
            this.$_router.push(`/pages/index/category?category=${id}`);
        }
    }
};
</script>

<style lang="scss">
page {
    background-color: #f6f7fa;
}
</style>

<style lang="scss" scoped>
/deep/.cl-noticebar {
    width: 160rpx;
    background-color: transparent !important;
    padding: 0;

    &__box {
        margin: 0;
    }

    &__scroller {
        height: 70rpx !important;
    }

    &__text {
        height: 70rpx !important;
        line-height: 35rpx !important;
        font-size: 20rpx;
        color: #fff;
    }
}

.popup-rules {
    /deep/.__h2 {
        display: block;
        text-align: center;
        margin-bottom: 20rpx;
    }

    /deep/.__div {
        line-height: 50rpx;
    }
}

.popup-red-package {
    /deep/.cl-popup {
        background-color: transparent;
        overflow: visible;

        &__container {
            padding: 0;
        }
    }

    /deep/.cl-countdown__number {
        background-color: transparent !important;
        margin: 0 !important;
        padding: 0;
        font-size: 22rpx;
        border-radius: 10rpx;
    }
}

.time-box {
    display: flex;
    align-items: center;
    color: #ffffff;
    &__li {
        width: 36rpx;
        height: 40rpx;
        border-radius: 8rpx;
        background-color: #f70114;
        font-size: 24rpx;
        text-align: center;
        line-height: 40rpx;
    }
    &__pian {
        margin: 0 8rpx;
        color: #f70114;
    }
}

.page-index {
    font-size: 24rpx;

    /deep/.category-bar {
        position: fixed;
        left: 0;
    }

    .header {
        position: relative;
        overflow: hidden;
        height: 630rpx;

        .subsidy-bg {
            display: block;
            width: 100%;
        }

        .top-tips {
            display: flex;
            height: 40rpx;
            position: absolute;
            top: 114rpx;
            left: 10rpx;
            width: calc(100% - 20rpx);
            transform: scale(0.8);

            &__cover {
                height: 60rpx;
                width: 100%;
                position: absolute;
            }

            &__item {
                flex: 1;
                text-align: center;
                color: #fff;
                font-size: 24rpx;
                position: relative;
                top: 14rpx;

                &.active {
                    color: #fa5240;
                }
            }
        }

        .countdown {
            display: flex;
            align-items: center;
            position: relative;
            top: 1rpx;

            /deep/.cl-countdown__number {
                background-color: #f70114;
                margin: 0 4rpx !important;
                color: #fff;
                padding: 0;
                font-size: 22rpx;
                border-radius: 10rpx;
            }
        }

        .subsidy-price {
            height: 150rpx;
            width: calc(100% - 40rpx);
            position: absolute;
            bottom: 180rpx;
            left: 20rpx;
            z-index: 2;

            &-bg {
                height: 100%;
                width: 100%;
                position: absolute;
                left: 0;
                top: 0;
            }

            .detail {
                position: relative;
                padding-left: 160rpx;
                color: #e62a0d;
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 140rpx;

                .value {
                    font-size: 55rpx;
                    font-weight: bold;

                    &::after {
                        content: '元';
                        font-size: 28rpx;
                        margin-left: 5rpx;
                    }
                }

                .countdown {
                    margin-right: 30rpx;

                    /deep/.cl-countdown {
                        &__number {
                            height: 36rpx;
                            line-height: 36rpx;
                        }
                    }
                }
            }

            .swiper-box {
                position: absolute;
                z-index: 10;
                top: 50rpx;
                right: 25rpx;
            }
        }
    }

    .container {
        position: relative;
        padding: 20rpx;
        margin-top: -180rpx;
        padding-bottom: 50rpx;
        .rank-goods{
            margin-top: 20rpx;
        }
        .goods-list {
            margin: 0 -20rpx;
            position: relative;
            // background-color: #ff5532;

            &__header {
                height: 80rpx;
                display: flex;
                align-items: center;
                color: #fff;
                padding: 0 30rpx;

                & > text {
                    font-size: 32rpx;
                    margin-right: 20rpx;
                    color: #333333;
                }

                .countdown {
                    display: flex;
                    align-items: center;
                    position: relative;
                    height: 40rpx;
                    width: 262rpx;

                    /deep/.cl-countdown {
                        &__number {
                            background-color: transparent;
                            font-size: 24rpx;
                            padding: 0;
                            margin: 0;
                            color: #ff1919;
                            min-width: 34rpx;
                        }

                        &__splitor {
                            color: #ff1919;
                        }
                    }

                    .det {
                        position: absolute;
                        right: 22rpx;
                    }

                    .bg {
                        position: absolute;
                        left: 0;
                        height: 40rpx;
                        width: 262rpx;
                    }
                }
            }
        }
    }
}

.popup-totb {
    /deep/.cl-popup {
        background-color: transparent;
        &__container {
            padding-bottom: 0;
        }
    }

    &__cover {
        height: 600rpx;
        width: 600rpx;
    }

    &__tips {
        position: absolute;
        left: -5rpx;
        bottom: 235rpx;
        width: 100%;
        text-align: center;

        & > text {
            display: block;
            font-size: 30rpx;
            margin-bottom: 10rpx;
        }
    }

    &__btn {
        height: 70rpx;
        line-height: 70rpx;
        width: 200rpx;
        color: #fff;
        background-color: #f70114;
        box-shadow: 0 6rpx 10rpx 2rpx rgba(0, 0, 0, 0.4);
        font-size: 26rpx;
        border-radius: 70rpx;
        position: relative;
        top: -130rpx;
        letter-spacing: 1rpx;
        margin: 0 auto;
        border: 0;

        &::after {
            border: 0;
        }
    }

    &__close {
        position: absolute;
        right: 0rpx;
        top: 100rpx;
        height: 60rpx;
        width: 60rpx;
    }
}

.pupop-copy-tkl {
    letter-spacing: 1px;

    /deep/.cl-popup {
        border-radius: 10rpx;

        &__container {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 50rpx 100rpx;
        }
    }

    image {
        height: 80rpx;
        width: 80rpx;
        margin: 0 0 50rpx 0;
    }

    .fa {
        font-size: 28rpx;
    }

    .fb {
        font-size: 24rpx;
        color: #999;
        margin-top: 50rpx;
    }

    .countdown {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;

        /deep/.cl-countdown__number {
            background-color: transparent;
            margin: 0;
            padding: 0;
            font-size: 24rpx;
        }
    }

    .cl-icon-close {
        position: absolute;
        right: 20rpx;
        top: 20rpx;
        font-size: 40rpx;
        color: #666;
    }
}

/deep/.cl-countdown__splitor {
    position: relative;
    top: -2rpx;
}
</style>
